package cn.tedu.cwfw.comment.service.impl;

import cn.tedu.cwfw.comment.mapper.CommentMapper;
import cn.tedu.cwfw.comment.pojo.dto.CommentQuery;
import cn.tedu.cwfw.comment.pojo.entity.Comment;
import cn.tedu.cwfw.comment.pojo.vo.CommentVO;
import cn.tedu.cwfw.comment.service.CommentService;
import cn.tedu.cwfw.comment.pojo.dto.SaveCommentFrom;
import cn.tedu.cwfw.dynamic.mapper.DynamicMapper;
import cn.tedu.cwfw.dynamic.pojo.entity.Dynamic;
import cn.tedu.cwfw.dynamic.pojo.vo.DynamicVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 添加评论业务层
     * @param saveCommentFrom 评论参数
     */
    @Override
    public void saveComment(SaveCommentFrom saveCommentFrom) {
        log.debug("评论请求业务:入参{}",saveCommentFrom);
        Comment comment = new Comment();
        BeanUtils.copyProperties(saveCommentFrom,comment);
        comment.setCreateTime(new Date());
        comment.setLevel(saveCommentFrom.getParentId()+1);
        commentMapper.addComment(comment);

        // 更新动态评论数
        Dynamic dynamic = new Dynamic();
        dynamic.setId(saveCommentFrom.getDynamicId());
        dynamic.setCommentCount(dynamic.getCommentCount()+1);
        dynamicMapper.updateDynamic(dynamic);
    }

    /**
     * 删除评论业务层
     * @param id 评论id
     */
    @Override
    public void deleteComment(Long id) {
        log.debug("删除评论请求业务:id={}",id);
        CommentVO commentVO = commentMapper.selectCommentById(id);
        DynamicVO dynamicVO = dynamicMapper.selectDynamicById(commentVO.getDynamicId());
        Dynamic dynamic = new Dynamic();
        dynamic.setId(dynamicVO.getId());
        dynamic.setCommentCount(dynamicVO.getCommentCount()-1);
        dynamicMapper.updateDynamic(dynamic);
        commentMapper.deleteComment(id);
    }

    /**
     * 点赞业务层
     * @param id 评论id
     */
    @Override
    public void likeComment(Long id) {
        log.debug("点赞请求业务:id={}",id);
        CommentVO commentVO = commentMapper.selectCommentById(id);
        Comment comment = new Comment();
        comment.setId(commentVO.getId());
        comment.setLikeCount(commentVO.getLikeCount()+1);
        commentMapper.updateComment(comment);
    }

    /**
     * 获取评论业务层
     * @param commentQuery 评论参数
     * @return
     */
    @Override
    public List<CommentVO> getComment(CommentQuery commentQuery) {
        log.debug("获取评论请求业务:入参{}",commentQuery);
        List<CommentVO> list = commentMapper.selectComment(commentQuery);
        log.debug("获取评论请求业务层：入参:{},出参{}",commentQuery,list);
        return list;
    }
}
